package com.xxljobdemo.xxljobdemo.job;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxljobdemo.xxljobdemo.domain.UserMobilePlan;
import com.xxljobdemo.xxljobdemo.mapper.UserMobilePlanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/04/02/10:59
 * @Description:
 */
@Component
public class SimpleXxlJob {


    @Autowired
    private UserMobilePlanMapper userMobilePlanMapper;

    /**
     * 运行模式使用bean
     */
    @XxlJob("demoJobHandler")
    public void demoJobHandler() {
        System.out.println("执行定时任务，执行时间为：" + new Date());
    }


    /**
     * 分片广播
     * @throws Exception
     */
    @XxlJob("sendMsgHandler")
    public void sendMsgHandler() throws Exception{
        System.out.println("任务开始时间:"+new Date());
        int shardTotal = XxlJobHelper.getShardTotal();  // 分片总数
        int shardIndex = XxlJobHelper.getShardIndex(); // 当前分片序号
        List<UserMobilePlan> userMobilePlans = null;
        if(shardTotal==1){
            //如果没有分片就直接查询所有数据
            userMobilePlans = userMobilePlanMapper.selectAll();
        }else{
            userMobilePlans = userMobilePlanMapper.selectByMod(shardIndex,shardTotal);
        }
        System.out.println("处理任务数量:"+userMobilePlans.size());
        Long startTime = System.currentTimeMillis();
        userMobilePlans.forEach(item->{
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("任务结束时间:"+new Date());
        System.out.println("任务耗时:"+(System.currentTimeMillis()-startTime)+"毫秒");
    }
}
